<template>
  <div class="vacancy-distribution">
    <div class="title">资产空置分布</div>
    <div class="chart-container" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
});

const chartRef = ref(null);
let chart = null;

const initChart = () => {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  updateChart();

  window.addEventListener("resize", () => {
    chart?.resize();
  });
};

const updateChart = () => {
  if (!chart || !props.data) return;

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "10px",
      right: "10px",
      bottom: "70px",
      top: "20px",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: props.data.map((item) => item.name),
      axisLabel: {
        interval: 0,
        rotate: 30,
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        type: "bar",
        data: props.data.map((item) => item.value),
        itemStyle: {
          color: "#1890ff",
        },
      },
    ],
  };

  nextTick(() => {
    chart.setOption(option);
    chart.resize();
  });
};

watch(
  () => props.data,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        if (!chart) {
          initChart();
        } else {
          updateChart();
        }
      });
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

onUnmounted(() => {
  window.removeEventListener("resize", () => {
    chart?.resize();
  });
  chart?.dispose();
});
</script>

<style lang="scss" scoped>
.vacancy-distribution {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
  }

  .chart-container {
    flex: 1;
    overflow: hidden;
  }
}
</style>
